/* eslint-disable default-case */
/* eslint-disable array-callback-return */
import { message } from 'antd';
import {
  getEmpList,
  getPdInfoList,
  checkQuotationName,
  getInfoCust,
  getDetail,
  getQuotationHistory,
  deleteListData,
  changeListState,
  getDownloadInfo,
  getUploadProgress,
  uploadFile,
  getRespUserList,
} from '@/services/quotation';
import { matchDict } from '@/utils/utils';
import * as service from '@/services/socket';
import { SocketActions, batchTaskFactory } from '@/models/socket';
import { delay } from '@/utils/dva';
// 非常重要属性
const namespace = 'quotation';
const ModelAddEmp = {
  namespace,
  state: {
    formFieldsValue: {},
    expandForm: false,
    pageData: {
      // 列表数据
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    // 修改历史记录数据
    quotationHistoryList: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    quotationQuery: {
      sendSuppId: undefined, // 签约方
      custId: undefined, // 客户名称
      contId: undefined, // 供应商合同
      quoName: undefined, // 报价单名称
      pdId: undefined, // 产品id
      serType: undefined, // 服务类型
      taxRatio: '0.001', // 填写的税率
    },
    supplyList: [], // 签约方列表
    customerNameList: [], // 客户名称列表
    supplyContList: [], // 供应商合同列表
    contList: [], // 本地--商务合同列表
    productList: [], // 产品列表数据
    productDataAll: [], // 打包的产品数据
    suppReplaceCorpId: '', // 当前角色所在公司id
    suppIds: '', // 下一步默认的当前角色所在公司id
    taxes: '1', // 是否含税报价
    method: '1', // 报价方式
    suppList: [
      {
        // 打包产品列表
        id: new Date().getTime(),
        listQuoPd: [],
      },
    ],
    proarridList: [], // 部分打包产品列表
    childproarr: [], // 子打包产品
    packList: [],
    isSerTypeDisabled: false, // 服务类型
    isEntrust: false, // 供应商合同默认委托，不可更改
    isLocalDisabled: false, // 本地客户入口 服务类型 不可更改
    comType: '1', // 公司类型
    detailInfo: {},
    batchQuery: {
      // 批量上传数据
      progressPercent: 0,
    },
    resultInfo: {
      // 结果数据必传
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorParams: null, // 下载错误数据参数
      errorUrl: '/csApi/crmquo/dowoloadErrorExist', // 下载错误信息地址
    },
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    valuesArr: ['custId', 'quoId', 'custContId', 'quoNo', 'quoState', 'suppId', 'primId'],
    respUserList: [],
    tempType: null,
  },
  effects: {
    // 获取列表
    *fetchList({ payload }, { call, put }) {
      const response = yield call(getEmpList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 历史记录
    *fetchHistory({ payload }, { call, put }) {
      const response = yield call(getQuotationHistory, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getEditQuotationHistory',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getEditQuotationHistory',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '获取修改报价单历史记录信息：服务端错误！'}`);
      }
    },
    // 选择产品数据列表
    *getPdInfoList({ payload, callback }, { call }) {
      const response = yield call(getPdInfoList, payload);
      if (callback) {
        callback(response);
      }
    },
    // 校验报价单名称的重复
    *getCheckName({ payload, callback }, { call }) {
      const response = yield call(checkQuotationName, payload);
      if (callback) {
        callback(response);
      }
    },
    // 查唯一的客户数据
    *getInfoCust({ payload, callback }, { call }) {
      const response = yield call(getInfoCust, payload);
      if (callback) {
        callback(response);
      }
    },
    // 详情数据
    *fetchDetail(
      {
        payload: { quoId, dictCode },
      },
      { call, put }
    ) {
      const response = yield call(getDetail, { quoId });
      yield put({
        type: 'updateModelData',
        payload: {
          detailInfo: {},
        },
      });
      if (response.success) {
        const detailInfo = response.data;
        if (detailInfo.packList.length) {
          detailInfo.packList.map(pack => {
            if (pack.listQuoPd.length) {
              pack.listQuoPd.map(pd => {
                if (pd.listAttr.length) {
                  pd.listAttr.map(attr => {
                    const temp = attr;
                    temp.attrValName = [];
                    temp.name = '';
                    if (attr.attrValList.length) {
                      attr.attrValList.forEach(item => {
                        attr.attrValName.push(matchDict(dictCode[attr.dictType], item));
                      });
                      temp.name = attr.attrValName.join(',');
                    }
                  });
                }
              });
            }
          });
        }
        yield put({
          type: 'updateModelData',
          payload: {
            detailInfo,
          },
        });
      } else {
        message.warning(response.message || '获取报价单信息：服务端错误');
      }
    },
    // 报价单列表删除
    *deleteData({ payload }, { call }) {
      const response = yield call(deleteListData, payload);
      return response;
    },
    // 修改列表状态
    *changeState({ payload }, { call }) {
      const response = yield call(changeListState, payload);
      return response;
    },
    *getDownloadInfo({ payload }, { call, put }) {
      const response = yield call(getDownloadInfo, payload);
      yield put({
        type: 'updateQuery',
        payload,
      });
      if (response.success) {
        const fileInfo = response.data.split('|');
        yield put({
          type: 'publicdata/setFileDownload',
          payload: { fileId: fileInfo[0], fileName: fileInfo[1] },
        });
      } else {
        message.warning(`${response.message || '服务端错误：获取下载模板失败！'}`);
      }
    },
    // 获取上传进度数据
    *getUploadProgress({ payload, callback }, { call, put }) {
      const response = yield call(getUploadProgress, payload);
      if (response.success) {
        yield put({
          type: 'updateQuery',
          payload: { progressPercent: response.data.successProp },
        });
      }
      if (callback && typeof callback === 'function') {
        callback(response);
      }
    },
    // 上传文件:批量进度
    uploadFileWithProgress:[
     function* ({ payload }, { call, put }) {
      try {
        const response = yield call(uploadFile, payload);
        if (response.success) {
          yield put({
            type: 'setTempType',
            payload: { tempType: response.data && response.data.tempType },
          });
          // 不是100表示需要走队列
          if (response.data && response.data.successProp !== 100) {
            const { batchId } = response.data;
            const batchTask = batchTaskFactory(batchId, namespace, 'handleBatchTask');

            yield put.resolve({
              type: `socket/${SocketActions.subSocketChannel}`,
              payload: {
                batchTask,
              },
            });
            // 订阅成功后再触发进度条
            yield put({
              type: 'updateModelData',
              payload: { showProgress: true },
            });
          } else {
            yield put({
              type: 'handleBatchTask',
              payload: response.data,
            });
          }
        } else {
          message.warning(response.message || '上传文件错误：服务器端错误');
        }

        // 无需返回response对象
      } catch (e) {
        console.error(e);
      }
    },
    { type: 'throttle', ms: 10000 }
  ],
    *handleBatchTask({ payload }, { put, select }) {
      const state = yield select(s => s.quotation);
      const { tempType } = state;
      let { showProgress, resultInfo, currentStep } = state;
      showProgress = true;
      if (payload.successProp >= 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
          tempType,
        };
        resultInfo = { ...resultInfo, ...payload };
        currentStep += 1;
        showProgress = false;
        // 先更新进度
        yield put({
          type: 'updateBatchTask',
          payload: {
            progressPercent: payload.successProp,
            resultInfo,
          },
        });
        yield delay(3000);
        // 再更新状态
        yield put({
          type: 'updateBatchTask',
          payload: {
            currentStep,
            showProgress,
          },
        });
      } else {
        yield put({
          type: 'updateBatchTask',
          payload: { progressPercent: payload.successProp, resultInfo },
        });
      }
    },
    // 获取所属客服列表
    *fetchRespUserList({ payload }, { call, put }) {
      const response = yield call(getRespUserList, payload);
      yield put({
        type: 'updateModelData',
        payload: {
          respUserList: [],
        },
      });
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: {
            respUserList: Array.isArray(response.data) ? response.data : [],
          },
        });
      } else {
        message.warning(response.message || '获取所属客服数据：服务端错误');
      }
    },
  },

  reducers: {
    // 获取列表
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 获取修改历史记录列表数据
    getEditQuotationHistory(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        quotationHistoryList: { list, total: data.totalCount, current: currentPage, pageSize },
      };
    },
    // 返回模版信息
    getTemplate(state, { payload }) {
      return {
        ...state,
        fileId: payload.split('|')[0],
        fileName: payload.split('|')[1],
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 设置查询时保存的值
    updateTabListQuery(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    // 更新参数
    updateQuery(state, { payload }) {
      return {
        ...state,
        quotationQuery: { ...state.quotationQuery, ...payload },
        batchQuery: { ...state.batchQuery, ...payload },
      };
    },
    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    setTempType(state, { payload }) {
      return {
        ...state,
        tempType: payload.tempType,
      };
    },
  },
  subscriptions: {
    socket({ dispatch }) {
      service.listen(async action => {
        // 判断是否自己命名空间的回调

        if (action.namespace === namespace) {
          switch (action.type) {
            case 'task':
              await dispatch({
                type: 'handleBatchTask',
                payload: action.data,
              });
              await dispatch({
                type: `socket/${SocketActions.handleUpdateBatchTask}`,
                payload: {
                  successProp: action.data.successProp,
                  batchId: action.data.batchId,
                },
              });
              // 全局保存
              dispatch({
                type: 'publicdata/updateBatchTaskData',
                payload: action.data,
              });
              break;
          }
        }
      }, namespace);
    },
  },
};

export default ModelAddEmp;
